package com.sale.goods.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.goods.domain.GoodsInvoiceInto;
import com.sale.goods.domain.GoodsTurn;
import com.sale.goods.domain.dto.GoodsTurnDto;
import com.sale.goods.domain.vo.GoodsTurnVo;
import com.sale.goods.mapper.GoodsTurnMapper;
import com.sale.goods.service.IGoodsTurnService;
import com.sale.system.api.RemoteAccountManagementService;
import com.sale.system.api.RemoteCodeService;
import com.sale.system.api.RemoteReviewService;
import com.sale.system.api.RemoteStaffManagementService;
import com.sale.system.api.domain.SysBalance;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.domain.vo.SysAuditHistoryVo;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 转账单实现类
 * @Date 23-07-28
 * @Author hl
 **/
@RequiredArgsConstructor
@Service
public class GoodsTurnServiceImpl implements IGoodsTurnService {

    private final GoodsTurnMapper goodsTurnMapper;

    @DubboReference
    private final RemoteReviewService remoteReviewService;

    @DubboReference
    private final RemoteCodeService remoteCodeService;

    @DubboReference
    private final RemoteStaffManagementService remoteStaffManagementService;

    @DubboReference
    private final RemoteAccountManagementService remoteAccountManagementService;

    /**
     * 分页查询转账单
     *
     * @param goodsTurnVo 转账单,pageQuery 分页参数
     * @return TableDataInfo<GoodsTurnDto>
     */
    @Override
    public TableDataInfo<GoodsTurnDto>  selectTurnList(GoodsTurnVo goodsTurnVo, PageQuery pageQuery) {
        Page<GoodsTurnDto> page = goodsTurnMapper.selectTurnList(pageQuery.build(), this.buildQueryWrapper(goodsTurnVo));
        List<SysDictData> netArray = CacheUtils.get(CacheNames.SYS_DICT, "bill_state");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<GoodsTurnDto> list = page.getRecords();
        //职员
        Map<String, String> map = remoteStaffManagementService.selectAllStaffManagement();
        for (GoodsTurnDto dto:
        list) {
            dto.setTurnStatusDict(netMap.get(dto.getTurnStatus()));
            dto.setTurnPeople(map.get(dto.getTurnPeople()));
        }
        return TableDataInfo.build(page);
    }

    /**
     * 新增转账单
     *
     * @param goodsTurnVo 转账单
     * @return int
     */
    @Override
    public int insertTurn(GoodsTurnVo goodsTurnVo) throws Exception {
        GoodsTurn turn = new GoodsTurn();
        BeanUtils.copyProperties(goodsTurnVo, turn);
        turn.setTurnStatus(1);
        String authorityCoding = remoteCodeService.authorityCoding("finance:transfer:list");
        if (StringUtils.isEmpty(authorityCoding)) {
            throw new GlobalException("未进行单据配置,单据编码生成失败");
        }
        turn.setTurnCode(authorityCoding);
        return goodsTurnMapper.insert(turn);
    }

    /**
     * 修改转账单
     *
     * @param goodsTurnVo
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTurnEdit(GoodsTurnVo goodsTurnVo) {
        if(goodsTurnVo.getTurnStatus().equals("4")){
            SysAuditHistoryVo vo = new SysAuditHistoryVo();
            vo.setPerms("finance:transfer:examine");
            vo.setAuditDoc(goodsTurnVo.getTurnCode());
            int is = remoteReviewService.editHistory(vo);
            if (is == 0) {
                throw new GlobalException("修改失败,未找到审核历史!");
            }
        }
        GoodsTurn turn = new GoodsTurn();
        BeanUtils.copyProperties(goodsTurnVo, turn);
        turn.setTurnStatus(1);
        return goodsTurnMapper.updateById(turn);
    }

    /**
     * 删除转账单
     *
     * @param turnId
     * @return int
     */
    @Override
    public int deleteTurnById(Long turnId) {
        return goodsTurnMapper.deleteById(turnId);
    }

    /**
     * 查询单个转账单
     *
     * @param turnId
     * @return GoodsTurn
     */
    @Override
    public GoodsTurn selectTurnById(long turnId) {
        return goodsTurnMapper.selectById(turnId);
    }

    /**
     * 提交审核
     *
     * @param turnId
     * @return int
     */
    @Override
    public int submitReview(Long turnId) {
        GoodsTurn goodsTurn = goodsTurnMapper.selectById(turnId);
        int status = goodsTurn.getTurnStatus();
        if(status != 1){
            throw new GlobalException("只有待提交状态才能进行提交审核");
        }
        GoodsTurn goods= new GoodsTurn();
        goods.setTurnStatus(2);
        goods.setTurnId(turnId);
        return goodsTurnMapper.updateById(goods);
    }

    /**
     * 撤销审核
     *
     * @param turnId
     * @return int
     */
    @Override
    public int deleteReview(Long turnId) {
        GoodsTurn goodsTurn = goodsTurnMapper.selectById(turnId);
        int status = goodsTurn.getTurnStatus();
        if(status != 2){
            throw new GlobalException("只有待审核状态才能进行提交审核");
        }
        GoodsTurn goods= new GoodsTurn();
        goods.setTurnStatus(1);
        goods.setTurnId(turnId);
        return goodsTurnMapper.updateById(goods);
    }

    /**
     * 审核单据
     *
     * @param goodsTurnVo
     * @return int
     */
    @Override
    public int goodSExamineReview(GoodsTurnVo goodsTurnVo) throws Exception {
        SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
        Long id = goodsTurnVo.getTurnId();
        GoodsTurn goodsTurn = goodsTurnMapper.selectById(id);
        String perms = "finance:transfer:examine";
        sysAuditHistoryVo.setPerms(perms);
        sysAuditHistoryVo.setModuleType(3);
        sysAuditHistoryVo.setAuditState(goodsTurnVo.getAuditState());
        sysAuditHistoryVo.setAuditRemarks(goodsTurnVo.getAuditOpinion());
        sysAuditHistoryVo.setAuditDoc(goodsTurn.getTurnCode());
        sysAuditHistoryVo.setUserId(LoginHelper.getUserId());
        int data = remoteReviewService.getSequence(sysAuditHistoryVo);
        if (data == 0) {
            throw new GlobalException("未对该审核进行配置");
        }
        //1:通过，2：审核中，3：没权限 4:该人已经审核过
        GoodsTurn goods = new GoodsTurn();
        goods.setTurnId(id);
        switch (data) {
            case 1:
                if (goodsTurnVo.getAuditState() == 2) {
                    goods.setTurnStatus(4);
                } else {
                    goods.setTurnStatus(5);
                }
                break;
            case 2:
                goods.setTurnStatus(3);
                break;
            case 3:
                if (data == 0) {
                    throw new GlobalException("不具备审核权限");
                }
                break;
            case 4:
                if (data == 0) {
                    throw new GlobalException("请勿重复审核");
                }
                break;
        }
        if(goodsTurnVo.getAuditState()==1){
            SysBalance sys = new SysBalance();
            sys.setBalance(goodsTurn.getTurnAmount());
            sys.setAccountsId(Long.parseLong(goodsTurn.getTurnOutAccount()));
            int i = remoteAccountManagementService.editBalance2(sys);
            if (i>0) {
                sys.setAccountsId(Long.parseLong(goodsTurn.getTurnIntoAccount()));
                i = remoteAccountManagementService.editBalance(sys);
                if(i==0){
                    throw new GlobalException("未回传余额,请重试");
                }
            }else{
                throw new GlobalException("未回传余额,请重试");
            }
        }
        //审核人
        goods.setExamineBy(LoginHelper.getUsername());
        //审核日期
        goods.setExamineTime(new Date());
        return goodsTurnMapper.updateById(goods);
    }

    private Wrapper<GoodsTurnVo> buildQueryWrapper(GoodsTurnVo goodsTurnVo) {
        Map<String, Object> params = goodsTurnVo.getParams();
        QueryWrapper<GoodsTurnVo> wrapper = Wrappers.query();
        wrapper
            .like(ObjectUtil.isNotNull(goodsTurnVo.getTurnCode()), "t1.turn_code", goodsTurnVo.getTurnCode())
            .like(StringUtils.isNotBlank(goodsTurnVo.getTurnIntoAccount()), "t1.turn_Into_account", goodsTurnVo.getTurnIntoAccount())
            .eq(StringUtils.isNotBlank(goodsTurnVo.getTurnOutAccount()), "t1.turn_out_account", goodsTurnVo.getTurnOutAccount())
            .eq(StringUtils.isNotBlank(goodsTurnVo.getTurnStatus()), "t1.turn_status", goodsTurnVo.getTurnStatus()).between(goodsTurnVo.getBeginTime() != null && goodsTurnVo.getEndTime() != null,
                "t1.turn_time", goodsTurnVo.getBeginTime(), goodsTurnVo.getEndTime());
        return wrapper;
    }

}
